package com.yungu.swift.api.base;

import com.yungu.swift.api.config.ApplicationConfig;
import com.yungu.swift.api.utils.RsaUtil;
import com.yungu.swift.base.ResponseData;
import com.yungu.swift.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.net.URLEncoder;


/**
 * @author cuixiuyin
 * @description 对controllerRequestBody返回值加密
 */
@Slf4j
@Order(0)
@ControllerAdvice
public class ResponseApiAdvice implements ResponseBodyAdvice {


    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        try {
            //这边截取到如果是ResponseData的返回值，则对data进行加密
            if (body instanceof ResponseData) {
                String bodyStr = JsonUtils.writeJsonStr(((ResponseData) body).getData());
                String rsaStr = RsaUtil.encryptByPublic(bodyStr, RsaUtil.MOBILE_PUBLIC_KEY);
                return URLEncoder.encode(rsaStr, "UTF-8");
            }
        } catch (Exception e) {
            log.error("ApiResponseBodyAdvice JsonUtils writeJsonStr error.", e);
        }
        return "adviceError";
    }

    @Override
    public boolean supports(MethodParameter methodParameter, Class clas) {
        if (ApplicationConfig.SERVER_CONFIG.getSafety().getEncrypt()) {
            //获取当前处理请求的controller的方法
            String methodName = methodParameter.getMethod().getName();
            // 不拦截/不需要处理返回值 的方法
            return !methodName.contains("uploadImage") && !methodName.contains("adminDriUpload")
                    && !methodName.contains("adminDriUpload") && !methodName.contains("adminDriLogin")
                    && !methodName.contains("drawQrCodeGift") && !methodName.contains("inviteDriver")
                    && !methodName.contains("listActivity");
        }
        return false;
    }
}